

enum ReflectKey {
    'KeyW' = 'W',
    'KeyA' = 'A',
    'KeyS' = 'S',
    'KeyD' = 'D',
    'Space' = 'Space',
    'ArrowUp' = 'Up',
    'ArrowDown' = 'Down',
    'ArrowLeft' = 'Left',
    'ArrowRight' = 'Right',
}

enum PressedType {
    Click = 'click',
    Press = 'press'
}

enum Axias {
    horizontal = 'horizontal',
    vertical = 'vertical'
}

enum Horizontal {
    'ArrowLeft' = -1,
    'ArrowRight' = 1
}

enum Vertical {
    'ArrowUp' = 1,
    'ArrowDown' = -1
}



class Input {
    public static instance: Input;
    private static keyCode: string;
    private static pressedType: PressedType | null;
    private static pressKeyDuration = 500;
    private static startPressTime: number = 0;
    public static getInstance() {
        if (!Input.instance) {
            Input.instance = new Input();
            window.addEventListener('keydown', (e) => {
                Input.startPressTime = Input.startPressTime === 0 ? Date.now() : Input.startPressTime;
                Input.keyCode = e.code;
            })

            window.addEventListener('keyup', (e) => {
                // 按键按下超过 pressKeyDuration ，为长按

                if (Date.now() - Input.startPressTime > Input.pressKeyDuration) {
                    Input.pressedType = PressedType.Press;
                } else {
                    Input.pressedType = PressedType.Click;
                }
                Input.startPressTime = 0;

            })
        }
        return Input.instance

    }
    //  点按
    public getClick(keyCode: string): boolean {
        if (Input.pressedType === PressedType.Press) return false;
        const isPressed = keyCode === ReflectKey[Input.keyCode]?.toLocaleLowerCase();


        if (isPressed) {
            console.log(`点按${keyCode}`);
            Input.keyCode = null;
            Input.pressedType = null;
        }
        return isPressed;
    }
    // 长按
    public getPressed(keyCode: string) {
        if (Input.pressedType === PressedType.Click) return false;
        const isPressed = keyCode === ReflectKey[Input.keyCode]?.toLocaleLowerCase();
        if (isPressed) {
            console.log(`长按${keyCode}`);
            Input.keyCode = null;
            Input.pressedType = null;
        }
        return isPressed;
    }
    public getButtonAxias(direction: string) {
        let directionValue = 0;
        if (direction === Axias.horizontal) {
            directionValue = this.getHorizontalInput(Input.keyCode)
        } else if (direction === Axias.vertical) {
            directionValue = this.getVerticalInput(Input.keyCode);
        }
        Input.keyCode = null;
        return directionValue
    }

    public getHorizontalInput(direction: string) {
        return Horizontal[direction];
    }
    public getVerticalInput(direction: string) {
        return Vertical[direction];
    }
}


export default Input.getInstance()